package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.gateway.bo.user.UserRegisterInfo;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IMemberService;
import com.mall.user.IUserVerifyService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Map;

import static com.mall.user.intercepter.TokenIntercepter.ACCESS_TOKEN;

/**
 * @program: cs-mall_35th
 * @description: 用户模块
 * @author: Weiwei Liu
 * @create: 2021-12-11 19:40
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference(timeout = 6000, retries = 0, check = false)
    IMemberService memberService;
    //    @Reference(timeout = 3000, retries = 0, check = false)
//    IAddressService addressService;
    @Reference(timeout = 3000, retries = 0, check = false)
    IKaptchaService kaptchaService;

    @Reference(timeout = 3000, retries = 0, check = false)
    IUserVerifyService userVerifyService;


    // 注册
    @Anoymous
    @PostMapping("register")
    public ResponseData register(@RequestBody UserRegisterInfo info, HttpServletRequest httpServletRequest) {

        String email = info.getEmail();         // 保证唯一
        String userName = info.getUserName();   // 保证唯一
        String userPwd = info.getUserPwd();     // 需要加密
        String captcha = info.getCaptcha();     // 需要验证
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");  //uuid


        // 先验证用户是否存在，username、phone、email唯一性
        UniqueKeyMemberRequest uniqueKeyMemberRequest = new UniqueKeyMemberRequest();
        uniqueKeyMemberRequest.setEmail(email);
        uniqueKeyMemberRequest.setUsername(userName);
        UniqueKeyMemberResponse uniqueKeyMemberResponse = memberService.uniqueKeyMember(uniqueKeyMemberRequest);
        if (SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode().equals(uniqueKeyMemberResponse.getCode())) {
            // 返回用户名已存在
            return new ResponseUtil().setErrorMsg(uniqueKeyMemberResponse.getMsg());
        } else if (SysRetCodeConstants.REQUISITE_PARAMETER_NOT_EXIST.getCode().equals(uniqueKeyMemberResponse.getCode())) {
            // 用户名和邮箱不能为null
            return new ResponseUtil().setErrorMsg(uniqueKeyMemberResponse.getMsg() + ":用户和邮箱");
        } else if (SysRetCodeConstants.USER_REGISTER_EMAIL_INVALID.getCode().equals(uniqueKeyMemberResponse.getCode())) {
            // 邮箱格式不正确
            return new ResponseUtil().setErrorMsg(uniqueKeyMemberResponse.getMsg());
        } else if (SysRetCodeConstants.USER_REGISTER_FAILED.getCode().equals(uniqueKeyMemberResponse.getCode())) {
            // 注册失败，请联系管理员
            return new ResponseUtil().setErrorMsg(uniqueKeyMemberResponse.getMsg());
        }


        // 用户不重复，再验证传过来的验证码,uuid获取不到？为啥
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(kaptchaCodeResponse.getCode())) {
            // 验证码不正确
            return new ResponseUtil().setErrorMsg(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());
        }


        // 向用户表中插入一条记录
        // 插入成功后，向用户发送激活邮件
        InsertMemberRequest insertMemberRequest = new InsertMemberRequest();
        insertMemberRequest.setEmail(email);
        insertMemberRequest.setPassword(userPwd);
        insertMemberRequest.setUsername(userName);
        insertMemberRequest.setUuid(uuid);
        InsertMemberResponse insertMemberResponse = memberService.insertMember(insertMemberRequest);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(insertMemberResponse.getCode())) {
            // 插入失败联系管理员
            return new ResponseUtil().setErrorMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
        }


        // 向用户验证表中插入一条记录，携带uuid和username
        // username被uniqueKeyMember校验，uuid被validateKaptchaCode校验，所以不需要参数校验
        addUserVerify(userName, uuid);


        return new ResponseUtil().setData(null);

    }

    private void addUserVerify(String userName, String uuid) {
        // 插入成功，向用户验证表中插入一条记录
        UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
        userVerifyRequest.setUserName(userName);
        userVerifyRequest.setUuid(uuid);
        UserVerifyResponse userVerifyResponse = userVerifyService.insertUserVerify(userVerifyRequest);

    }


    // 注册激活
    @Anoymous
    @GetMapping("verify")
    public ResponseData register(String uid, String username) {

        // 根据uuid更新tb_user_verify
        UpdateUserVerifyRequest updateUserVerifyRequest = new UpdateUserVerifyRequest();
        updateUserVerifyRequest.setUuid(uid);
        updateUserVerifyRequest.setIsVerify("Y");
        UpdateUserVerifyResponse updateUserVerifyResponse = userVerifyService.updateUserVerify(updateUserVerifyRequest);


        // 根据username更新tb_member
        VerifyMemberRequest verifyMemberRequest = new VerifyMemberRequest();
        verifyMemberRequest.setUsername(username);
        verifyMemberRequest.setIsVerify("Y");
        VerifyMemberResponse updateMemberResponse = memberService.verifyMember(verifyMemberRequest);

        if (updateUserVerifyResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode()) && updateMemberResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            // 两个都成功激活成功
            return new ResponseUtil().setData(null);
        }

        // 只要有一个更新失败，激活失败
        return new ResponseUtil().setErrorMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());

    }


    // 登陆
    @Anoymous
    @PostMapping("login")
    public ResponseData login(@RequestBody Map map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        String username = (String) map.get("userName");
        String password = (String) map.get("userPwd");
        String captcha = (String) map.get("captcha");
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");  //uuid

        // 验证用户名和密码是否正确，以及是否被激活
        LoginMemberRequest loginMemberRequest = new LoginMemberRequest();
        loginMemberRequest.setUsername(username);
        loginMemberRequest.setPassword(password);
        UserLoginResponse userLoginResponse = memberService.login(loginMemberRequest);
        if (SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode().equals(userLoginResponse.getCode())) {
            // 用户名尚未激活
            return new ResponseUtil().setErrorMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
        } else if (!SysRetCodeConstants.SUCCESS.getCode().equals(userLoginResponse.getCode())) {
            // 用户名或者密码不正确
            return new ResponseUtil().setErrorMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
        }


        // 验证传过来的验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getCode())) {
            // 验证码不正确
            return new ResponseUtil().setErrorMsg(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());
        }


        // 登录成功之后把token放入cookie
        String token = userLoginResponse.getToken();
        Cookie cookie = CookieUtil.genCookie(ACCESS_TOKEN, token, "/", 3600);
        CookieUtil.setCookie(httpServletResponse, cookie);

        return new ResponseUtil().setData(userLoginResponse);

    }

    // 验证登陆
    @Anoymous
    @GetMapping("login")
    public ResponseData login(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        // 获取token
        String token = CookieUtil.getCookieValue(httpServletRequest, ACCESS_TOKEN);

        // 校验token
        VerifyUserLoginResponse verifyUserLoginResponse = memberService.login(token);

        if (SysRetCodeConstants.SUCCESS.getCode().equals(verifyUserLoginResponse.getCode())) {

            return new ResponseUtil().setData(verifyUserLoginResponse.getLoginDto());
        }

        return new ResponseUtil().setErrorMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());

    }


    // 退出
    @Anoymous
    @GetMapping("loginOut")
    public ResponseData logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        // 清除cookie里面的token
        String token = CookieUtil.getCookieValue(httpServletRequest, ACCESS_TOKEN);

        if (token != null) {

            Cookie cookie = CookieUtil.genCookie(ACCESS_TOKEN, null, "/", 0);
            CookieUtil.setCookie(httpServletResponse, cookie);

        }

        return new ResponseUtil().setData(null, SysRetCodeConstants.SUCCESS.getMessage());

    }


}
